<template>
  <common-edit-dialog
    :title="dialogTitle"
    :visible.sync="dialogShow"
    @submit="submitForm"
    :button-loading="isPersistenceLoading"
    @cancel="close('onlyClose')"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
      @submit.native.prevent
    >
      <el-row :gutter="18">
        <!-- 数据源名称 -->
        <el-col :span="12">
          <el-form-item label="数据源名称" prop="datasoureName">
            <common-input
              v-model="form.datasoureName"
              :maxlength="16"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <!-- 数据源类型 -->
        <el-col :span="12">
          <el-form-item label="数据源类型" prop="datasourceType">
            <el-select
              v-model="form.datasourceType"
              placeholder="请选择"
              clearable
              style="width: 100%"
              @change="datasourceTypeChange"
            >
              <el-option
                v-for="(item, index) in dbType"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- URL -->
        <el-col :span="24" v-if="form.datasourceType === 'API'">
          <el-form-item label="URL" prop="url">
            <common-input
              :verify="false"
              v-model="form.url"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <!-- IP地址 -->
        <el-col :span="12" v-if="form.datasourceType !== 'API'">
          <el-form-item label="IP地址" prop="ip">
            <common-input
              v-model="form.ip"
              :verify="false"
              placeholder="支持IPV4/IPV6格式"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.datasourceType !== 'API'">
          <el-form-item label="端口" prop="port">
            <common-input-number :max-length="5" v-model="form.port" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.datasourceType !== 'API'">
          <el-form-item label="用户名" prop="username">
            <common-input
              v-model="form.username"
              :maxlength="16"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <common-add-dept
            ref="commonAddDept"
            :deptListParams="deptListParams"
            @getCheckedDeptId="getCheckedDeptId"
            :deptId="form.deptId"
          ></common-add-dept>
        </el-col>

        <el-col :span="12" v-if="form.datasourceType !== 'API'">
          <el-form-item
            label="密码"
            prop="password"
            :rules="canChangePass ? rules.password : []"
            v-if="!isEdit"
          >
            <template v-if="isEdit">
              <div v-show="canChangePass" style="display: flex">
                <common-pwd-input
                  :verify="false"
                  :type="'password'"
                  v-model="form.password"
                  placeholder="请输入"
                />
                <el-button
                  style="margin-left: 8px"
                  type="primary"
                  plain
                  @click="changePassword(false)"
                  >取消
                </el-button>
              </div>
              <div style="display: flex">
                <el-button
                  v-show="!canChangePass"
                  type="primary"
                  plain
                  @click="changePassword(true)"
                  >重置</el-button
                >
              </div>
            </template>
            <template v-else>
              <common-pwd-input
                :verify="false"
                :type="'password'"
                v-model="form.password"
                placeholder="请输入"
              />
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.datasourceType === 'MYSQL'" key="MYSQL">
          <el-form-item
            label="数据库名称"
            prop="databaseName"
            :rules="otherRule.databaseName"
          >
            <common-input
              :verify="false"
              v-model="form.databaseName"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.datasourceType === 'ES'" key="ES1">
          <el-form-item
            label="索引名称"
            prop="databaseName"
            :rules="otherRules.databaseName"
          >
            <common-input
              :verify="false"
              v-model="form.databaseName"
              placeholder="请输入"
              :disabled="this.isEs"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.datasourceType === 'ES'" key="ES2">
          <el-form-item
            label="协议"
            prop="accessSchema"
            :rules="otherRules.accessSchema"
          >
            <el-select
              v-model="form.accessSchema"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option label="HTTP" value="http"></el-option>
              <el-option label="HTTPS" value="https"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </common-edit-dialog>
</template>

<script>
import { mapState } from "vuex";
import {
  db_addApi,
  db_addMysql,
  db_addEs,
  db_edit,
} from "@/api/management/echart/db.js";
import { portRule } from "@/utils/formRules";
import BaseIndex from "@/mixins/BaseIndex";
import { encode } from "@/utils/aesUtils";
import { validateIP, validateURL } from "@/utils/formValidates";

export default {
  components: {},
  props: {
    isEs: {
      type: Boolean,
      default: null,
    },
    deptListParams: {
      type: Array,
      default: () => [],
    },
  },
  mixins: [BaseIndex],
  data() {
    return {
      isPersistenceLoading: false,
      dialogTitle: "新增", // 标题
      dialogShow: false, // 是否显示
      form: {
        datasoureName: "",
        databaseName: "",
        datasourceType: "",
        ip: "",
        port: 80,
        username: "",
        password: "",
        deptId: "",
        accessSchema: "",
      },
      rules: {
        datasoureName: [
          { required: true, message: "请输入数据源名称", trigger: "blur" },
        ],
        datasourceType: [
          { required: true, message: "请选择数据源类型", trigger: "blur" },
        ],
        ip: [
          { required: true, message: "请输入IP地址", trigger: "blur" },
          {
            required: true,
            message: "IP地址错误，支持IPV4/IPV6格式",
            validator: validateIP,
            trigger: "blur",
          },
        ],
        url: [
          {
            required: true,
            message: "请输入URL",
            trigger: "blur",
          },
          {
            required: true,
            message: "URL格式错误",
            validator: validateURL,
            trigger: "blur",
          },
        ],
        port: portRule,
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入数据库密码", trigger: "blur" },
        ],
        // deptId: [
        //   { required: true, message: '请选择组织', trigger: 'blur' }
        // ],
      },
      otherRules: {
        databaseName: [
          { required: true, message: "请输入索引名称", trigger: "blur" },
        ],
        accessSchema: [
          { required: true, message: "请选择协议", trigger: "blur" },
        ],
      },
      otherRule: {
        databaseName: [
          { required: true, message: "请输入数据库名称", trigger: "blur" },
        ],
      },
      isEdit: false,
    };
  },
  computed: {
    ...mapState({
      dbType: (state) => state.dict.dbType,
    }),
  },
  methods: {
    datasourceTypeChange() {
      this.form.accessSchema = "";
    },
    getCheckedDeptId(val) {
      this.form.deptId = val;
    },
    /**
     * 关闭
     */
    close(onlyClose) {
      this.$refs.form.resetFields();
      this.dialogShow = false;
      if (!onlyClose) {
        this.$emit("refresh");
      }
    },
    /**
     * 显示
     */
    show(data) {
      this.dialogTitle = data.id ? "编辑数据源" : "新增数据源";
      this.dialogShow = true;
      this.form = data.id ? data : this.$options.data().form;
      this.isEdit = !!data.id;
      this.form.password = "";
      // console.log(this.form);
    },

    validateByFormName(formName) {
      return new Promise((resolve, reject) => {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            reject();
          }
        });
      });
    },
    validateForm() {
      return this.validateByFormName("form");
    },
    validateOtherForm() {
      // return this.validateByFormName('otherRules')
    },
    validateOthersForm() {
      // return this.validateByFormName('otherRule')
    },
    /**
     * 提交
     */
    submitForm() {
      Promise.all([this.validateForm()]).then(() => {
        const data = { ...this.form };
        data.password = data.password ? encode(data.password) : "";
        if (!data.password) delete data.password;
        if (data.datasourceType !== "ES") data.accessSchema = "";
        if (data.id) {
          if (!this.isPersistenceLoading) {
            this.isPersistenceLoading = true;
            db_edit(data)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.close();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.isPersistenceLoading = false;
                this.canChangePass = false;
              });
          }
        } else {
          if (data.datasourceType == "API") {
            if (!this.isPersistenceLoading) {
              this.isPersistenceLoading = true;
              db_addApi(data)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("新增成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("新增失败", res.msg).then();
                  }
                })
                .finally(() => {
                  this.isPersistenceLoading = false;
                });
            }
          } else if (data.datasourceType == "MYSQL") {
            if (!this.isPersistenceLoading) {
              this.isPersistenceLoading = true;
              db_addMysql(data)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("新增成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("新增失败", res.msg).then();
                  }
                })
                .finally(() => {
                  this.isPersistenceLoading = false;
                });
            }
          } else if (data.datasourceType == "ES") {
            if (!this.isPersistenceLoading) {
              this.isPersistenceLoading = true;
              db_addEs(data)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("新增成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("新增失败", res.msg).then();
                  }
                })
                .finally(() => {
                  this.isPersistenceLoading = false;
                });
            }
          }
        }
      });
    },
    changePassword(flag) {
      this.changePassword2(flag);
      if (!flag) {
        this.form.password = "";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.el-col {
  padding-left: 9px;
  padding-right: 9px;
}
</style>
